package com.lostandfound.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lostandfound.pojo.Result;
import com.lostandfound.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
//        log.info("preHandle...");
        String jwt = request.getHeader("token");
        if (!StringUtils.hasText(jwt)) {
            Result result = Result.error("NOT_LOGIN");
            objectMapper.writeValue(response.getWriter(),result);
            return false;
        }
        try {
            JwtUtils.parseJWT(jwt);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            Result result = Result.error("NOT_LOGIN");
            objectMapper.writeValue(response.getWriter(),result);
            return false;
        }


    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
//                           ModelAndView modelAndView) throws Exception {
//        log.info("preHandle...");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
//                                Exception ex) throws Exception {
//        log.info("afterCompletion...");
//    }
}